import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Modal, Select } from 'antd';
import { TableC } from '../../../../comps';
import { connect } from 'dva';
import config from '../../../../comps/business/tradingMarket/config.js';
@connect(({ OTCOptionLifeCycleManagementM }) => ({ OTCOptionLifeCycleManagementM }))
export default class OTCOptionLifeCycleTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      tableData: {},
      loading: false,
    };
  }
  componentDidMount() {
    const { searchObj } = this.props;
    if (searchObj) {
      this.getData({
        ...searchObj,
        numInPage: 10,
        currentPage: 1,
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchObj) !== JSON.stringify(this.props.searchObj) || nextProps.num !== this.props.num) {
      this.getData({
        ...nextProps.searchObj,
        numInPage: 10,
        currentPage: 1,
      });
    }
  }
  //表格分页
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.getData({
      ...this.props.searchObj,
      numInPage: pageSize,
      currentPage: current,
    });
  };

  // 获取数据
  getData = (searchObj) => {
    this.setState({
      loading: true,
    });
    this.props.dispatch({
      type: 'OTCOptionLifeCycleManagementM/queryOptionLifeList',
      payload: {
        ...searchObj,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            tableData: { ...data.data },
            loading: false,
          });
        } else {
          this.setState({
            tableData: {},
            loading: false,
          });
        }
      },
    });
  };

  //执行事件
  onIncidentExecute = (e) => {
    Modal.confirm({
      title: '是否确认执行该事件?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.setState({
          loading: true,
        });
        this.props.dispatch({
          type: 'OTCOptionLifeCycleManagementM/updateOptionStatus',
          payload: {
            ...e,
            date: this.props.searchObj.date,
          },
          callback: (type, data) => {
            if (type == 'success') {
              const { currentPage, numInPage } = this.state.tableData.pageInfo || {};

              this.getData({
                ...this.props.searchObj,
                numInPage: numInPage,
                currentPage: currentPage,
              });
            } else {
              this.setState({
                loading: false,
              });
            }
          },
        });
      },
      onCancel() {},
    });
  };

  //交易详情
  showTransactionDetails = (e) => {
    this.props.showShareOption(e.bundleId);
  };
  //事件类型改变
  onTypeChange = (value, row, text) => {
    this.setState({
      tableData: {
        ...this.state.tableData,
        dataSource: this.state.tableData.dataSource?.map((x) => {
          if (x.id === row.id) {
            return Object.assign(x, { ...row, type: value });
          } else {
            return x;
          }
        }),
      },
    });
  };

  render() {
    const { optionEnentType, OTCOptionLifeCycleManagementM } = this.props;
    const { OTC_OPTION_BOOK_OPTIONSTRUCT = [], OTC_OPTION_BOOK_OPTIONTYPE = [], MAAT_OPTION_UNDERLYING_TYPE = [] } = OTCOptionLifeCycleManagementM.dictionary;
    const { tableData = {}, loading } = this.state;
    const { columns = [], dataSource = [], pageInfo = {} } = tableData;
    const newColums =
      columns.length > 0
        ? [
            ...columns
              .map((x) => {
                x.width = 100;

                if (x.key == 'underlying') {
                  x.width = 180;
                }
                if (x.key == 'productName' || x.key == 'underlying') {
                  x.width = 180;
                }
                if (x.key == 'counterparty' || x.key == 'tradeDate' || x.key == 'expiryDate') {
                  x.width = 120;
                }
                if (x.key === 'bookId') {
                  return {
                    ...x,
                    render: (text, record) => <a onClick={() => this.showTransactionDetails(record)}>{text}</a>,
                  };
                }
                if (x.key === 'optionStruct') {
                  return {
                    ...x,
                    render: (text, row) => OTC_OPTION_BOOK_OPTIONSTRUCT.filter((x) => x.code == text)[0]?.value || '--',
                  };
                }
                if (x.key === 'optionType') {
                  return {
                    ...x,
                    render: (text, row) => OTC_OPTION_BOOK_OPTIONTYPE.filter((x) => x.code == text)[0]?.value || '--',
                  };
                }
                if (x.key == 'underlying') {
                  x.render = (val, data) => {
                    let exchange = config.filter((item) => {
                      return item.value == data.exchangeCode;
                    });
                    return data.tradingCode + '-' + data.secuabbr + '-' + exchange[0]?.title;
                  };
                }
                if (x.key === 'underlyingType') {
                  return {
                    ...x,
                    render: (text, row) => MAAT_OPTION_UNDERLYING_TYPE.filter((x) => x.code == text)[0]?.value || '--',
                  };
                }
                if (x.key === 'status') {
                  return {
                    ...x,
                    width: 150,
                    fixed: 'right',
                    render: (text, row) => (
                      <Select placeholder='请选择' value={row.type} onChange={(e) => this.onTypeChange(e, row, text)} style={{ width: '100%' }}>
                        {text && optionEnentType.map((x) => text.indexOf(x.value) > -1 && <Select.Option value={x.value}>{x.title}</Select.Option>)}
                      </Select>
                    ),
                  };
                }

                if (['notional', 'barrier1', 'barrier2', 'underlyingPrice', 'exerciseAmount'].indexOf(x.key) > -1) {
                  return {
                    ...x,
                    type: 'money',
                  };
                }
                return x;
              })
              .filter((x) => x.key !== 'id'),
            {
              title: '操作',
              dataIndex: 'edit',
              key: 'edit',
              type: 'operate',
              fixed: 'right',
              width: 150,
              operates: [
                {
                  title: '事件执行',

                  onClick: this.onIncidentExecute,
                  rules: {
                    disabled: { items: [{ key: 'type', value: [undefined], relation: ['='] }] },
                  },
                },
                {
                  title: '交易详情',
                  disabled: false,
                  onClick: this.showTransactionDetails,
                },
              ],
            },
          ]
        : [];

    return (
      <TableC
        columns={newColums}
        dataSource={dataSource}
        current={Number(pageInfo.currentPage)}
        pageSize={pageInfo.numInPage}
        total={pageInfo.total}
        scroll={{ x: 'max-content' }}
        selfScrollY={true}
        rowKey='id'
        loading={loading}
        onChange={this.handleTableChange}
      />
    );
  }
}
